import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

import {routes} from '@/router/routes.js';
import vmBus from "@/router/vmBus.js";

const routerMethods = ['push', 'replace']
routerMethods.forEach(method => {
  const originalCall = VueRouter.prototype[method]
  VueRouter.prototype[method] = function(location, onResolve, onReject) {
    if (onResolve || onReject) {
      return originalCall.call(this, location, onResolve, onReject)
    }
    return originalCall.call(this, location).catch(err => err)
  }
})

const tokey = {
  userName: '',
  password: '',
};
let isshow = false;

const router = new VueRouter({
  routes: routes,
  
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 }
  },
});

vmBus("dataw", ({userName, password}) => {
  tokey.userName = userName + '';
  tokey.password = password + '';
});

// 前置路由守卫
router.beforeEach((to, from, next) => {
  
  if(to.name != "Login" && isshow) {
    if(tokey.userName === "666" && tokey.password === "123") {
      isshow = false;
      next({path: "/home"});
    }else {
      vmBus("accountAndPasswordareIncorrect", false);
    }

    next({path: "/login"});  
  }else {
    next();
  }

});

// 后置路由守卫
router.afterEach((to, from) => {
  if(to.path === "/login") { window.document.title = "登录" }
  else if(to.path === "/home") { window.document.title = "主页" }
  else if(to.name === "Detail") { window.document.title = "城市详情" }
});



export default router;